package com.alks.function.service.impl.pcfactoryquery;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.aop.RedisLock;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.MysqlUtil;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.common.utils.excelUtils.FreezeTopRowsHandler;
import com.alks.entity.data.entity.PcLotDetail;
import com.alks.entity.data.entity.PcStitchDetail;
import com.alks.entity.data.entity.PcStitchFrozen;
import com.alks.entity.data.entity.PcStitchFrozenLog;
import com.alks.entity.data.enums.biocontrol.StitchDeptEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.chengKong.produce.PcLotStatusCount2Dto;
import com.alks.function.data.dto.chengKong.produce.PcStitchStatusDto;
import com.alks.function.data.dto.pcfactoryquery.*;
import com.alks.function.data.request.factoryquery.StitchHeadRequest;
import com.alks.function.data.request.factoryquery.StitchStockRequest;
import com.alks.function.data.vo.biocontrol.deptwork.ReportStitchDailyVO;
import com.alks.function.data.vo.biocontrol.deptwork.ReportStitchDailyVO2;
import com.alks.function.data.vo.pcfactoryWork.DailyExportVo;
import com.alks.function.data.vo.stock.StitchStkFlowVo;
import com.alks.function.handler.excel.ReportStitchDailyStyleHandler;
import com.alks.function.mapper.pcfactoryquery.FT_QR_PcStitchDetailMapper;
import com.alks.function.mapper.pcfactoryquery.FT_QR_PcStitchFrozenLogMapper;
import com.alks.function.mapper.pcfactoryquery.FT_QR_PcStitchFrozenMapper;
import com.alks.function.mapper.pcfactoryquery.FT_QR_PcStitchStatusMapper;
import com.alks.function.mapper.stockdept.pcfactorystockquery.SD_SQ_PcLotDetailMapper;
import com.alks.function.service.pcfactoryquery.IPcStitchDetailService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ms
 * @since 2023-08-17
 */
@Service
@Slf4j
public class PcStitchDetailServiceImpl extends ServiceImpl<FT_QR_PcStitchDetailMapper, PcStitchDetail> implements IPcStitchDetailService {
    @Autowired
    FT_QR_PcStitchDetailMapper stitchMapper;
    @Autowired
    SD_SQ_PcLotDetailMapper lotDetailMapper;
    @Autowired
    private FT_QR_PcStitchStatusMapper pcStitchStatusMapper;
    @Autowired
    private FT_QR_PcStitchDetailMapper pcStitchDetailMapper;
    @Autowired
    private FT_QR_PcStitchFrozenMapper pcStitchFrozenMapper;
    @Autowired
    private FT_QR_PcStitchFrozenLogMapper pcStitchFrozenLogMapper;


    @Override
    public ResponseInfo queryStitchStockHead(StitchStockRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        /*分页初始化*/
        if (request.getPageNum()==null||request.getPageSize()==null){
            request.setPageNum(1);
            request.setPageSize(10);
        }
        /*获取数据*/
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<PcStitchStockDto> stockDtos = stitchMapper.queryStitchStockHead(request,companyId);
        Page<PcStitchStockDto> page=(Page<PcStitchStockDto>) stockDtos;
        /*计算求和*/
//        Long sum = stitchMapper.queryStockCount(request);             //求所有满足条件的和
        Long sum=stockDtos.stream().mapToLong(PcStitchStockDto::getStockQty).sum();
        /*封装结果*/
        Map map=new HashMap();
        map.put("pageTotal",page.getTotal());
        map.put("stockSum",sum);
        map.put("dto",stockDtos);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo queryStitchStockDetail(String lotNo) {
        /*获取数据*/
        List<PcStitchDetail> qtyDtos= stitchMapper.queryStitchStockQty(lotNo);       //获取所有数量数据
        List<PcStitchDetailDto> detailDtos = stitchMapper.queryStitchStockDetail(lotNo);
        List<PcStitchStockDetailDto> stockDetailDtos= stitchMapper.queryStitchInDetail(lotNo);      //获取全部出入库明细数据
        /*处理明细数据*/
        PcStitchDetail inQtyDto = qtyDtos.stream().filter(a -> Objects.equals(a.getSlipType(), "I")).findFirst().orElse(null);
        PcStitchDetail outQtyDto = qtyDtos.stream().filter(a -> Objects.equals(a.getSlipType(), "O")).findFirst().orElse(null);
        /*针对SizeNo进行从小到大排序方便后续插入*/
        detailDtos.sort((a,b)-> Double.parseDouble(a.getSizeNo())>Double.parseDouble(b.getSizeNo())? 1:-1);
        int i=0;
        long inSum=0L;
        long outSum=0L;
        long stockSum=0L;
        long ordSum=0L;
        long ordShortSum=0L;
        long spShortSum=0L;
        long rpSum=0L;
        for (PcStitchDetailDto detailDto : detailDtos) {
            i++;
            /*反射获取QTY*/
            Float inQty =MysqlUtil.fieldOfList("qty",i,inQtyDto);            //入库数
            Float outQty = MysqlUtil.fieldOfList("qty",i,outQtyDto);         //出库数
            Float stockQty = inQty - outQty;                        //库存数
            /*QTY写入*/
            detailDto.setInQty(inQty);
            detailDto.setOutQty(outQty);
            detailDto.setStockQty(stockQty);
            /*处理入库和出库完成标志,完成则置Y*/
            inQty = inQty==null?0:inQty;
            outQty = outQty==null?0:outQty;
            int ordQty = detailDto.getOrdQty()==null?0:detailDto.getOrdQty();         //订单数
            detailDto.setInFlag(inQty>=ordQty ?"Y":null);     //入库标志
            detailDto.setOutFlag(outQty>=ordQty ?"Y":null);     //出库标志
            /*计算正单和预补欠数*/
            Integer surplusShort = detailDto.getSurplusShort()==null?0:detailDto.getSurplusShort(); //表中预补欠数
            float shortQty=ordQty-inQty;                          //计算总欠数
            if (shortQty>0) {
                /*计算正单欠数 总欠数-预补欠数*/
                detailDto.setOrdShort(shortQty > surplusShort ? ordQty - (inQty - surplusShort) : 0);
                /*计算正单欠数 总欠数-预补欠数*/
//                detailDto.setOrdShort(shortQty > surplusShort ? surplusShort : shortQty);
            }
            /*没有欠数则把预补欠数置零*/
            else  {
                detailDto.setSurplusShort(0);
                detailDto.setOrdShort(0f);
            }
            /*批次默认值*/
            if (inQty==0){
                detailDto.setLsNo(null);
                }
            else if (detailDto.getLsNo()==null) {
                detailDto.setLsNo(1);
            }
            /*求和*/
//            Integer rpQty = detailDto.getRePrint();
            int rpQty=0;
            float ordShort=detailDto.getOrdShort()==null?0f:detailDto.getOrdShort();
            int spShort = detailDto.getSurplusShort()==null?0:detailDto.getSurplusShort();
            inSum+=inQty;
            outSum+=outQty;
            stockSum+=stockQty;
            ordSum+=ordQty;
            rpSum+=rpQty;
            ordShortSum+= (long) ordShort;
            spShortSum+=spShort;
        }
        /*处理异常*/
        /*拆分出入库数据*/
        List<PcStitchStockDetailDto> inDtos=stockDetailDtos.stream().filter(a-> Objects.equals(a.getSlipType(),"I")).collect(Collectors.toList());
        List<PcStitchStockDetailDto> outDtos=stockDetailDtos.stream().filter(a-> Objects.equals(a.getSlipType(),"O")).collect(Collectors.toList());
        /*封装结果*/
        Map map =new HashMap();
        map.put("inSum",inSum);
        map.put("outSum",outSum);
        map.put("stockSum",stockSum);
        map.put("ordSum",ordSum);
        map.put("rpSum",rpSum);
        map.put("ordShortSum",ordShortSum);
        map.put("spShortSum",spShortSum);
        map.put("detailDtos",detailDtos);
        map.put("inDtos",inDtos);
        map.put("outDtos",outDtos);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo queryStitchDeptHead(StitchHeadRequest request) {
        /*获取数据*/
        List<StitchDeptHeadDto> headDtos =  stitchMapper.queryStitchDeptHead(request);
        /*分割出粗览数据*/
        List<Map<String, Object>> inDtosRough = headDtos.stream().filter(dto -> "I".equals(dto.getSlipType()))
                .collect(Collectors.groupingBy(dto -> dto.getDeptName().substring(0, 2))).entrySet().stream()   //根据部门名字前两个字分组
                .map(a -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("deptName", a.getKey());
                    map.put("qty", a.getValue().stream().mapToInt(StitchDeptHeadDto::getQty).sum());
                    return map;
                }).collect(Collectors.toList());
        /*分离出入库数据*/
        List<Map> inDtos = headDtos.stream().filter(a -> Objects.equals(a.getSlipType(), "I")).map(a->{
            Map<String, Object> map = new HashMap<>();
            map.put("deptName", a.getDeptName());
            map.put("qty", a.getQty());
            return map;
        }).collect(Collectors.toList());        //封装入库数据
        List<Map> outDtos = headDtos.stream().filter(a -> Objects.equals(a.getSlipType(), "O")).map(a->{
            Map<String, Object> map = new HashMap<>();
            map.put("deptName", a.getDeptName());
            map.put("qty", a.getQty());
            return map;
        }).collect(Collectors.toList());        //封装出库数据
        /*封装结果*/
        Map<String,Object> map=new HashMap<>(4);
        map.put("inDtos",inDtos);
        map.put("inDtosRough",inDtosRough);
        map.put("outDtos",outDtos);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo queryStitchDeptDetail(String deptName, String slipType) {
        /*获取数据*/
        List<StitchDeptDetailDto> detailDtos = stitchMapper.queryStitchDeptDetail(deptName,slipType);
        return ResponseInfo.ok(detailDtos);
    }

    @Override
    public List<DailyExportVo> dailyExportDateQuery(StitchHeadRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        /*获取数据*/
        List<DailyExportVo> voList = stitchMapper.dailyExportDateQuery(request,companyId);
        /*针车名称转换*/
        for (DailyExportVo vo : voList) {
            String[] split = vo.getInDeptName().split(",");
            StringBuilder deptName = new StringBuilder();
            for (String s : split) {
                s = StitchDeptEnum.fromGroupName(s)+",";
                deptName.append(s);
            }
            deptName.deleteCharAt(deptName.length() - 1);
            vo.setInDeptName(String.valueOf(deptName));
        }
        return voList;
    }

    @Override
    public void stitchStkExportQuery(StitchHeadRequest request, HttpServletResponse response) {
        String companyId = UserIdThread.get().getCompanyId();
        /*获取针车相关数据*/
        List<ReportStitchDailyVO2> stitchList = stitchMapper.stitchStkExportQuery(request,companyId);
        if (ArrayUtils.isEmpyt(stitchList)){
            throw new ServiceErrorException("暂无导出数据");
        }
        List<String> lotNoList = stitchList.stream()
                .map(ReportStitchDailyVO2::getLotNo)
                .filter(Objects::nonNull).distinct()
                .collect(Collectors.toList());
        /*获取订单补充数据*/
        List<PcLotDetail> lotDetailList = lotDetailMapper.getByLotNo(lotNoList,companyId);
        Map<String, List<PcLotDetail>> lotMap = lotDetailList.stream().collect(Collectors.groupingBy(PcLotDetail::getLotNo));
        int maxSize = 0;
        /*封装数据*/
        List<ReportStitchDailyVO> voList = new ArrayList<>(stitchList.size());
        for (ReportStitchDailyVO2 stitch : stitchList) {
            List<PcLotDetail> detailList = lotMap.get(stitch.getLotNo());
            if (ArrayUtils.isEmpyt(detailList)){
                continue;
            }
            ReportStitchDailyVO vo = new ReportStitchDailyVO();
            vo.setDeptName(stitch.getDeptName());
            vo.setLotNo(stitch.getLotNo());
            detailList = detailList.stream()
                    .sorted(Comparator.comparingDouble(pcLotDetail -> Double.parseDouble(pcLotDetail.getSizeNo())))
                    .collect(Collectors.toList());
            for (int i = 0; i < detailList.size(); i++) {
                String sizeNo = detailList.get(i).getSizeNo();
                /*直接用满参构造添加数据*/
                vo.getPoList().add(sizeNo);
                long orderQty = detailList.get(i).getOrderQty()==0?0:detailList.get(i).getOrderQty().longValue();
                long surplusQty = detailList.get(i).getSurplusQty()==null?0:detailList.get(i).getSurplusQty().longValue();
                vo.getOrderList().add(new ReportStitchDailyVO.PoData(sizeNo, orderQty));
                vo.getPrefixList().add(new ReportStitchDailyVO.PoData(sizeNo, surplusQty));
                int qtyIndex = i + 1;
                String qtyFieldName = "qty" + qtyIndex;
                String dailyQtyFieldName = "dailyQty" + qtyIndex;
                try {
                    /*获取总入库数量*/
                    Field field = ReportStitchDailyVO2.class.getDeclaredField(qtyFieldName);
                    Field dailyField = ReportStitchDailyVO2.class.getDeclaredField(dailyQtyFieldName);
                    field.setAccessible(true);
                    dailyField.setAccessible(true);
                    long qty = ((Float)field.get(stitch)).longValue();
                    long dailyQty = ((Float)dailyField.get(stitch)).longValue();
                    long shortQty = orderQty + surplusQty - qty;
                    vo.getAggregateList().add(new ReportStitchDailyVO.PoData(sizeNo, qty));
                    vo.getOweList().add(new ReportStitchDailyVO.PoData(sizeNo, shortQty));
                    vo.getDailyList().add(new ReportStitchDailyVO.PoData(sizeNo, dailyQty));
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    log.error("\n错误接口：stitchStkExportQuery\n错误原因：反射异常，字段名：{}或{}\n{}",qtyFieldName,dailyQtyFieldName,e.getMessage(),e);
                    throw new ServiceErrorException("程序异常");
                }

            }
            if (vo.getPoList().size() > maxSize) {
                maxSize = vo.getPoList().size();
            }
            vo.setTotal(detailList.stream()
                    .mapToLong(a->{
                        long orderQty = a.getOrderQty() == null ? 0 : a.getOrderQty().longValue();
                        long surplusQty = a.getSurplusQty() == null ? 0 : a.getSurplusQty().longValue();
                        return orderQty+surplusQty;
                    })
                    .filter(Objects::nonNull).sum());
            voList.add(vo);
        }

        String fileName = "荣信针车日报表";

        int rowIndex = 0;
        // 需要合并数据的行
        List<Integer> mergeRowIndex = new ArrayList<>();
        // 固定列
        String[] fixation = {"指令", "总数", "配码", "合计"};
        // 总列数
        int totalColumn = maxSize + fixation.length;
        List<List<String>> dataList = new ArrayList<>();
        // 添加表头数据
        dataList.add(Collections.nCopies(totalColumn, fileName));
        String dataStr = LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd");
        dataList.add(Collections.nCopies(totalColumn, "日期：" + dataStr));

        mergeRowIndex.add(rowIndex++);
        mergeRowIndex.add(rowIndex++);

        // 动态生成数据
        boolean tag = false;
        for (ReportStitchDailyVO dailyVO : voList) {
            List<String> d1 = new ArrayList<>(Arrays.asList(fixation));
            List<String> d2 = new ArrayList<>(Arrays.asList(fixation));

            // 插入动态列数据
            for (int i = 0; i < maxSize; i++) {
                d1.add(fixation.length - 1, dailyVO.getDeptName());
                if (i < dailyVO.getPoList().size()) {
                    d2.add(d2.size() - 1, dailyVO.getPoList().get(i));
                } else {
                    d2.add(d2.size() - 1, null);
                }
            }
            if (!tag) {
                d1.add("备注");
                tag = true;
            } else {
                d1.add("");
            }
            d2.add(null);
            dataList.add(d1);
            dataList.add(d2);
            dataList.add(data2List("订单数", dailyVO, dailyVO.getOrderList(), maxSize));
            dataList.add(data2List("预补数", dailyVO, dailyVO.getPrefixList(), maxSize));
            dataList.add(data2List("当日入库", dailyVO, dailyVO.getDailyList(), maxSize));
            dataList.add(data2List("累计入库", dailyVO, dailyVO.getAggregateList(), maxSize));
            dataList.add(data2List("欠数", dailyVO, dailyVO.getOweList(), maxSize));

            mergeRowIndex.add(rowIndex);
            mergeRowIndex.add(rowIndex + 1);
            rowIndex += 7; // 每7行为一组
        }

        // 定义需要合并的列
        int[] mergeColumnIndex = {0, 1, 2, totalColumn - 1};

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + "_" +System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream())
                    .registerWriteHandler(new ReportStitchDailyStyleHandler(mergeColumnIndex, mergeRowIndex.stream().mapToInt(Integer::intValue).toArray(), 2))
                    .registerWriteHandler(new FreezeTopRowsHandler(0, 2))
                    .sheet(fileName)
                    .doWrite(dataList);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 更新鞋面库存
     * @return
     */
    @Override
    public ResponseInfo updateStitchStatus() {

            //1.PC_STITCH_DETAIL_ATTACH有变化的数据（公司+指令+号码类型）
            List<PcLotStatusCount2Dto> list = pcStitchDetailMapper.getMismatchedLotNoList3(null);
            if(ObjectUtils.isEmpty(list)){
                log.info("没有指令号码总计数量变化，无需更新鞋面库存");
                return ResponseInfo.ok();
            }
            //2.有变化的指令遍历循环解决
            //3.分情况新增或者删除
            List<PcStitchStatusDto> statusUpdateList =  new ArrayList<>();
            List<PcStitchStatusDto> statusAddList = new ArrayList<>();
            for (PcLotStatusCount2Dto dto : list) {
                //4.如果创建时间为空代表是新增
                boolean isFlag = dto.getSysDate() == null;
                PcStitchStatusDto status = new PcStitchStatusDto();
                status.setCompanyId(dto.getCompanyId());
                status.setInQty(BigDecimal.valueOf(dto.getTotalInQty()));
                status.setOutQty(BigDecimal.valueOf(dto.getTotalOutQty()));
                status.setOrdQty(BigDecimal.valueOf(dto.getOrdQty()));
                status.setStkName(dto.getCompanyId().equals("BF") ? "荣信" : "荣越");
                status.setLotNo(dto.getLotNo());
                status.setStyle(dto.getStyle());
                status.setSeqNo(dto.getSeqNo());
                status.setSizeNo(dto.getSizeNo());
                if(isFlag){
                    //新增
                    statusAddList.add(status);
                }else{
                    //修改
                    statusUpdateList.add(status);
                }
            }
            if(ObjectUtils.isNotEmpty(statusAddList)){
                pcStitchStatusMapper.batchInsert(statusAddList);
            }
            if (ObjectUtils.isNotEmpty(statusUpdateList)){
                pcStitchStatusMapper.batchUpdate(statusUpdateList);
            }
            return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo deptNameBack(String search) {
        String companyId = UserIdThread.get().getCompanyId();
        LambdaQueryWrapper<PcStitchDetail> wrapper=new LambdaQueryWrapper<PcStitchDetail>()
                .select(PcStitchDetail::getDeptName)
                .like(StringUtils.isNotBlank(search),PcStitchDetail::getDeptName,search)
                .isNotNull(PcStitchDetail::getDeptName)
                .eq(PcStitchDetail::getCompanyId,companyId)
                .groupBy(PcStitchDetail::getDeptName);
        List<PcStitchDetail> stitchList = stitchMapper.selectList(wrapper);
        if (ArrayUtils.isEmpyt(stitchList)){
            return ResponseInfo.ok();
        }
        Set<String> deptNameSet = stitchList.stream()
                .map(PcStitchDetail::getDeptName)
                .collect(Collectors.toSet());
        return ResponseInfo.ok(deptNameSet);
    }

    @Override
    public List<StitchStkFlowVo> stitchStkFlowExport(StitchHeadRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        List<StitchStkFlowVo> voList = pcStitchStatusMapper.stitchStkFlowExport(request,companyId);
        return voList;
    }

    /**
     * 冻结指令(鞋面不能入库)
     * @param lotNoList
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo frozenStitch(List<String> lotNoList) {
        //只有用户名ID是GXX，LTF,LTFHF的账户可以冻结
        if (!UserIdThread.get().getUserId().matches("GXX|LTF|LTFHF")){
            throw new ServiceErrorException("用户没有权限,仅生控经理可操作！");
        }
        //判空
        if (CollectionUtils.isEmpty(lotNoList)){
            throw new ServiceErrorException("请选择数据");
        }
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        //获取数据有已经冻结的数据，请检查
        List<PcStitchFrozen> pcStitchFrozenList = pcStitchFrozenMapper.selectList(new LambdaQueryWrapper<PcStitchFrozen>()
                .in(PcStitchFrozen::getLotNo, lotNoList)
                .eq(PcStitchFrozen::getCompanyId,companyId)
        );
        if (CollectionUtils.isNotEmpty(pcStitchFrozenList)){
            throw new ServiceErrorException("存在指令被冻结记录，请检查");
        }

        //构建数据
        List<PcStitchFrozen> pcStitchFrozens = new ArrayList<>();
        List<PcStitchFrozenLog> pcStitchFrozenLogs = new ArrayList<>();

        for (String s : lotNoList) {
            PcStitchFrozen pcStitchFrozen = new PcStitchFrozen();
            pcStitchFrozen.setCompanyId(companyId);
            pcStitchFrozen.setLotNo(s);
            pcStitchFrozen.setSysUser(userName);
            pcStitchFrozen.setUpdateUser(userName);
            pcStitchFrozen.setSysDate(LocalDateTime.now());
            pcStitchFrozen.setUpdateDate(LocalDateTime.now());
            pcStitchFrozens.add(pcStitchFrozen);

            PcStitchFrozenLog pcStitchFrozenLog = new PcStitchFrozenLog();
            pcStitchFrozenLog.setCompanyId(companyId);
            pcStitchFrozenLog.setLotNo(s);
            pcStitchFrozenLog.setType(1);
            pcStitchFrozenLog.setSysUser(userName);
            pcStitchFrozenLog.setUpdateUser(userName);
            pcStitchFrozenLog.setSysDate(LocalDateTime.now());
            pcStitchFrozenLog.setUpdateDate(LocalDateTime.now());
            pcStitchFrozenLogs.add(pcStitchFrozenLog);
        }
        int count1 = pcStitchFrozenMapper.insertBatch(pcStitchFrozens);
        int count2 = pcStitchFrozenLogMapper.insertBatch(pcStitchFrozenLogs);

        if (count1 > 0 && count2 > 0) {
            return ResponseInfo.ok("冻结成功");
        } else {
            throw new ServiceErrorException("冻结失败");
        }
    }

    /**
     * 取消冻结指令
     * @param lotNoList
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo cancelFrozenStitch(List<String> lotNoList) {
        //只有用户名ID是GXX或者LTF或者LTFHF的账户可以冻结
        if (!UserIdThread.get().getUserId().matches("GXX|LTF|LTFHF")){
            throw new ServiceErrorException("用户没有权限,仅生控经理可操作！");
        }
        //判空
        if (CollectionUtils.isEmpty(lotNoList)){
            throw new ServiceErrorException("请选择数据");
        }
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        //获取数据有未冻结的数据，请检查
        List<PcStitchFrozen> pcStitchFrozenList = pcStitchFrozenMapper.selectList(new LambdaQueryWrapper<PcStitchFrozen>()
                .in(PcStitchFrozen::getLotNo, lotNoList)
                .eq(PcStitchFrozen::getCompanyId,companyId)
        );
        //pcStitchFrozenList不为空且传入的指令和查的长度不一致说明存在未冻结的
        if (CollectionUtils.isEmpty(pcStitchFrozenList) || pcStitchFrozenList.size() != lotNoList.size()){
            throw new ServiceErrorException("存在指令未冻结记录，请检查");
        }

        //构建数据
        List<PcStitchFrozenLog> pcStitchFrozenLogs = new ArrayList<>();

        for (String s : lotNoList) {
            PcStitchFrozenLog pcStitchFrozenLog = new PcStitchFrozenLog();
            pcStitchFrozenLog.setCompanyId(companyId);
            pcStitchFrozenLog.setLotNo(s);
            pcStitchFrozenLog.setType(0);
            pcStitchFrozenLog.setSysUser(userName);
            pcStitchFrozenLog.setUpdateUser(userName);
            pcStitchFrozenLog.setSysDate(LocalDateTime.now());
            pcStitchFrozenLog.setUpdateDate(LocalDateTime.now());
            pcStitchFrozenLogs.add(pcStitchFrozenLog);
        }
        int count1 = pcStitchFrozenMapper.deleteBatch(lotNoList,companyId);
        int count2 = pcStitchFrozenLogMapper.insertBatch(pcStitchFrozenLogs);

        if (count1 > 0 && count2 > 0) {
            return ResponseInfo.ok("解冻成功");
        } else {
            throw new ServiceErrorException("取消冻结失败");
        }
    }

    private List<String> data2List(String name, ReportStitchDailyVO dailyVO, List<ReportStitchDailyVO.PoData> dataList, int maxSize) {
        List<String> vd1 = new ArrayList<>();
        vd1.add(dailyVO.getLotNo());
        vd1.add(String.valueOf(dailyVO.getTotal()));
        vd1.add(name);
        Map<String, Long> dataMap = dataList.stream().collect(Collectors.toMap(ReportStitchDailyVO.PoData::getSizeNo, ReportStitchDailyVO.PoData::getQty));
        for (int i = 0; i < maxSize; i++) {
            if (i < dailyVO.getPoList().size()) {
                String po = dailyVO.getPoList().get(i);
                if (dataMap.containsKey(po)){
                    vd1.add(String.valueOf(dataMap.get(po)));
                } else {
                    vd1.add(null);
                }
            } else {
                vd1.add(null);
            }
        }
        vd1.add(String.valueOf(dataList.stream().mapToLong(ReportStitchDailyVO.PoData::getQty).sum()));
        vd1.add(null);
        return vd1;
    }
}
